package com.suredy.app.index.ctrl;

import java.io.IOException;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.suredy.Constants;
import com.suredy.core.ctrl.BaseCtrl;
import com.suredy.security.model.Role;
import com.suredy.security.model.User;
import com.suredy.security.service.RoleSrv;
import com.suredy.security.service.UserSrv;
import com.suredy.tools.checkcode.SuredyLoginCheckImage;

@Controller
public class LoginCtrl extends BaseCtrl {

	@Value("${role.proj_system_manager}")
	private String roleCodeOfSystemManager;
	@Value("${role.proj_creater}")
	private String roleCodeOfProjectCreater;
	@Value("${role.proj_deleter}")
	private String roleCodeOfProjectDeleter;
	@Value("${role.proj_updater}")
	private String roleCodeOfProjectUpdater;

	@Autowired
	private SuredyLoginCheckImage suredyLoginCheckImage;

	@Autowired
	private UserSrv userSrv;

	@Autowired
	private RoleSrv roleSrv;

	@RequestMapping(value = "/login", method = RequestMethod.GET)
	public String loginIndex() {
		this.getSession();
		return "login";
	}

	@RequestMapping(value = "/logout", method = RequestMethod.GET)
	public String logout() {
		this.clearSession();
		return "redirect:login";
	}

	@RequestMapping(value = "/login", method = RequestMethod.POST)
	public String doLogin(String userCode, String password, String checkCode, Boolean startupFlow, RedirectAttributes attributes) {
		// if (!this.isTheSameCheckCode(checkCode)) {
		// attributes.addFlashAttribute("err_msg", "校验码错误");
		// attributes.addFlashAttribute("uniqueCode", userCode);
		//
		// return "redirect:login";
		// }

		if (StringUtils.isBlank(userCode) || StringUtils.isBlank(password)) {
			attributes.addFlashAttribute("err_msg", "请正确填写用户名与密码");
			attributes.addFlashAttribute("uniqueCode", userCode);

			return "redirect:login";
		}

		User user = this.userSrv.getUser(userCode);

		if (user == null || !password.equals(user.getPassword())) {
			attributes.addFlashAttribute("err_msg", "用户名与密码不匹配");
			attributes.addFlashAttribute("uniqueCode", userCode);

			return "redirect:login";
		}

		this.setUser(user);

		if (startupFlow) {
			// TODO startup workflow server.
		}

		this.recordRoles(user);

		if (this.isOnlySystemManager()) {
			return "redirect:config/index";
		}

		return "redirect:index";
	}

	@RequestMapping("/check-img/{width}/{height}")
	public void checkImg(HttpServletResponse response, @PathVariable int width, @PathVariable int height) {
		try {
			String code = this.suredyLoginCheckImage.write(response.getOutputStream(), width, height);

			this.setSessionAttribute(Constants.SESSION_LOGIN_CHECK_CODE, code);
		} catch (IOException e) {
		}
	}

	private boolean isOnlySystemManager() {
		if (!this.isSystemManager())
			return false;

		if (this.getUserRoles() != null && this.getUserRoles().size() == 1)
			return true;

		return false;
	}

	private void recordRoles(User user) {
		// 初始化
		this.setSystemManager(false);
		this.setProjCreater(false);
		this.setProjDeleter(false);
		this.setProjUpdater(false);

		if (user == null)
			return;

		List<Role> roles = this.roleSrv.getByUserId(user.getId());

		if (roles == null)
			return;

		this.setUserRoles(roles);

		for (Role r : roles) {
			if (this.roleCodeOfSystemManager.equals(r.getCode())) {
				this.setSystemManager(true);
			} else if (this.roleCodeOfProjectCreater.equals(r.getCode())) {
				this.setProjCreater(true);
			} else if (this.roleCodeOfProjectDeleter.equals(r.getCode())) {
				this.setProjDeleter(true);
			} else if (this.roleCodeOfProjectUpdater.equals(r.getCode())) {
				this.setProjUpdater(true);
			}
		}
	}

}
